import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_taotaoshipin/app/app_controller.dart';
import 'package:flutter_taotaoshipin/http/dao/ad_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/ad_order_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/goods_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/order_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/pay_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/userinfo_dao.dart';
import 'package:flutter_taotaoshipin/model/drama_main_info_entity.dart';
import 'package:flutter_taotaoshipin/model/goods_list_entity.dart';
import 'package:flutter_taotaoshipin/model/pay_config_list_entity.dart';
import 'package:flutter_taotaoshipin/pages/purchase/apple_iap_info.dart';
import 'package:flutter_taotaoshipin/pages/purchase/purchase_type.dart';
import 'package:flutter_taotaoshipin/pages/purchase/view/confirm_open_dialog.dart';
import 'package:flutter_taotaoshipin/util/apple_pay_utils.dart';
import 'package:flutter_taotaoshipin/util/events.dart';
import 'package:flutter_taotaoshipin/value/constant.dart';
import 'package:flutter_taotaoshipin/value/global_config.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher_string.dart';

import 'top_purchase_state.dart';

class TopPurchaseController extends GetxController {
  final TopPurchaseState state = TopPurchaseState();

  TopPurchaseController({this.mainInfoEntity, int sort = 0}) {
    state.sort = sort;
  }

  // 主剧信息
  DramaMainInfoEntity? mainInfoEntity;

  // app生命周期
  late AppLifecycleListener _appLifecycleListener;

  /// 是否已经打开充值页面
  bool _hasOpenPayPage = false;

  /// 订单号
  String _orderId = '';

  /// 订单结果查询次数
  final int _maxCount = 3;
  int _currentCount = 1;

  // 支付结果监听
  StreamSubscription? _subscription;
  // 广告状态监听
  StreamSubscription? _adSubscription;
  // 广告位id
  String _adverId = '';
  // 广告商名字，gdt（优量汇）
  String adnName = '';

  @override
  void onInit() {
    super.onInit();
    // 监听app生命周期
    _appLifecycleListener = AppLifecycleListener(
      onResume: () {
        // 查询订单状态
        if (_hasOpenPayPage) {
          _hasOpenPayPage = false;
          _loadOrderQueryData(_orderId);
        }
      },
    );
    // 监听苹果支付结果
    _subscription =
        eventBus.on<ApplePayResult>().listen((event) {
      if (event.status == 'success') {
        UserinfoDao.updateCenter();
        Get.back(result: 1);
      }
    });
    // 广告状态监听
    // _adSubscription =
    //     gromoreEventChannel.receiveBroadcastStream().listen((event) {
    //   String type = event['type'];
    //   String method = event['callbackMethod'];
    //   Map data = event['result'];
    //   print(data['message']);
    //   if (type == 'TtspRewardVideoAd') {
    //     // 激励视频
    //     if (method == 'DidLoad') {
    //       TtspGromore.instance.showRewardAd();
    //     } else if (method == 'DidVisible') {
    //       // 获取广告商名字
    //       adnName = data['data']['adnName'];
    //       _loadAdEventCsj('2', ecpm: data['data']['ecpm']);
    //     } else if (method == 'DidPlayFinish') {
    //       _loadAdEventCsj('3');
    //     } else if (method == 'ServerRewardDidSucceed') {
    //       // 奖励发放成功
    //       AppController appController = Get.find();
    //       appController.increaseAdTodayLimit();
    //     } else if (method == 'DidClose') {
    //       if (Get.isDialogOpen == true) {
    //         Get.back(result: 2);
    //       }
    //     } else if (method == 'DidClick') {
    //       _loadAdEventCsj('1');
    //     }
    //
    //     if (data['code'] == -1) {
    //       EasyLoading.showToast(data['message'].toString());
    //     }
    //   }
    // });

    // 获取充值套餐列表
    _loadGoodsListData();
    // 获取充值模板
    _loadPayConfigListData();
  }

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    _subscription?.cancel();
    _adSubscription?.cancel();
    _appLifecycleListener.dispose();
    super.onClose();
  }

  /// 充值套餐列表
  Future<void> _loadGoodsListData() async {
    try {
      var result = await GoodsDao.list();
      if (result.code == 0) {
        if (result.data != null) {
          var list = result.data!;
          state.goodsList.clear();
          state.goodsList.addAll(list.where((element) =>
              element.goodsType == PurchaseType.subscription.value));
          state.goodsList.addAll(list.where((element) =>
              element.goodsType == PurchaseType.vip.value));

          state.currGood = state.goodsList.first;
        } else {
          EasyLoading.showToast('获取充值套餐列表失败');
        }
      } else {
        EasyLoading.showToast(result.message);
      }
    } catch (_) {
      EasyLoading.showToast('网络错误');
    }
  }

  /// 充值模板列表
  Future<PayConfigListEntity?> _loadPayConfigListData() async {
    PayConfigListEntity? entity;
    try {
      var result = await PayDao.configList();
      if (result.code == 0) {
        if (result.data != null) {
          state.payConfigListEntity = result.data!;
          state.currPayConfig = result.data!.list!.first;
        }
      } else {
        EasyLoading.showToast(result.message);
      }
    } catch (_) {
      EasyLoading.showToast('网络错误');
    }
    return entity;
  }

  /// 创建订单
  Future<void> _loadOrderCreateData(
    PayConfigListList payConfig,
    GoodsListEntity goodsListEntity,
  ) async {
    try {
      EasyLoading.show(status: '正在下单');
      var result = await OrderDao.create(
        goodsListEntity.amount!,
        goodsListEntity.id!,
        payConfig.code!,
        payConfig.account!,
        payPlatform: payConfig.platform,
      );
      if (result.code == 0) {
        if (result.data != null) {
          EasyLoading.dismiss();
          _orderId = result.data!.orderId!;
          // 数据不为空
          if (payConfig.code == 'apple_pay') {
            var jsonString = Uri.decodeFull(result.data!.payStr!);
            Map<String, dynamic> map = jsonDecode(jsonString);
            var uuid = map['uuid'];
            // 更新全局参数
            var payInfo = InAppPurchaseInfo(
              amount: goodsListEntity.amount,
              orderId: _orderId,
              productId: goodsListEntity.config?.appleGoodsId,
              uuid: uuid,
              payCode: payConfig.code,
            );
            AppController appController = Get.find();
            appController.updateApplePayInfo(payInfo);
            // 发起苹果支付
            await applePayUtils.startApplePay(
                goodsListEntity.config!.appleGoodsId!, uuid);
          } else if (payConfig.code == 'zfb_pay') {
            var url = Uri.decodeFull(result.data!.payStr!);
            _hasOpenPayPage = await launchUrlString(
              url,
              mode: LaunchMode.externalApplication,
            );
          } else if (payConfig.code == 'zfb_app_pay') {
            var url = Uri.decodeFull(result.data!.payStr!);
            _hasOpenPayPage = await launchUrlString(
              url,
              mode: LaunchMode.externalApplication,
            );
          } else {
            // var redirectUrl = Uri.encodeFull(
            // 'https://ts.933you.com/h5/#/pages/rechange/index?order_id=${result.data!.orderId}');
            var redirectUrl = Uri.encodeFull(Constant.urlScheme);
            var url =
                '${result.data!.payReferer}?to_url=${result.data!.payStr}&redirect_url=$redirectUrl';
            _hasOpenPayPage = await launchUrlString(
              url,
              mode: LaunchMode.externalApplication,
            );
          }
        } else {
          EasyLoading.showError('下单失败');
        }
      } else {
        EasyLoading.showError(result.message);
      }
    } catch (e) {
      EasyLoading.showError('网络错误');
    }
  }

  /// 订单状态主动查询
  Future<void> _loadOrderQueryData(String orderId,
      {bool retry = true}) async {
    try {
      EasyLoading.show(status: '订单查询中');
      var result = await OrderDao.query(orderId);
      if (result.code == 0) {
        if (result.data != null) {
          if (result.data!.status == 1) {
            EasyLoading.showSuccess('充值成功');
            // 充值成功，加载用户中心
            await UserinfoDao.updateCenter();
          } else {
            // 充值失败，重试3次
            if (retry) {
              _currentCount++;
              if (_currentCount > _maxCount) {
                _currentCount = 1;
                EasyLoading.showError('充值失败');
                return;
              } else {
                // 延迟1.5秒查询下一次
                Future.delayed(const Duration(milliseconds: 1500), () {
                  _loadOrderQueryData(orderId);
                });
              }
            } else {
              EasyLoading.showError('充值失败');
            }
          }
        } else {
          EasyLoading.showError('数据为空');
        }
      } else {
        EasyLoading.showError(result.message);
      }
    } catch (_) {
      EasyLoading.showError('网络错误');
    }
  }

  // 广告看剧
  watchAdToUnlock() {
    // _loadAdOrderCreateCsj();
  }

  /// 穿山甲激励广告下单
  // Future<void> _loadAdOrderCreateCsj() async {
    // var appController = Get.find<AppController>();
    // var adver = appController.csj.list
    //     ?.firstWhereOrNull((element) => element.adverType == '0');
    // if (adver != null && adver.adverId!.isEmpty) {
    //   return;
    // }
    // _adverId = adver!.adverId!;
    // try {
    //   EasyLoading.show(status: '加载广告中');
    //   var result = await AdOrderDao.createCsj(
    //       dramaId: '${mainInfoEntity?.id ?? 1}', adverId: _adverId);
    //   if (result.code == 0) {
    //     if (result.data != null) {
    //       var orderId = result.data!.orderId;
    //       await TtspGromore.instance.loadRewardAd(
    //         adId: _adverId,
    //         rewardName: mainInfoEntity?.title ?? '',
    //         rewardAmount: appController.csj.num!,
    //         userId: appController.localUserInfo.mId!,
    //         extra: orderId,
    //       );
    //       EasyLoading.dismiss();
    //       return;
    //     }
    //   }
    //   EasyLoading.showError('下单失败');
    // } catch (_) {
    //   EasyLoading.showError('网络错误');
    // }
  // }

  // Future<void> _loadAdEventCsj(String eventId, {String ecpm = ''}) async {
  //   try {
  //     var appController = Get.find<AppController>();
  //     var result = await AdDao.eventCsj(
  //       appId: appController.csj.appId!,
  //       adverId: _adverId,
  //       eventId: eventId,
  //       ecpm: ecpm,
  //     );
  //     if (result.code == 0) {
  //       if (result.data?.state == true) {
  //         print('广告事件回传成功');
  //         return;
  //       }
  //     }
  //     if (result.message.isNotEmpty) {
  //       print(result.message);
  //     } else {
  //       print('广告事件回传失败');
  //     }
  //   } catch (e) {
  //     print(e);
  //   }
  // }

  showTipsAndPay() {
    if (GlobalConfig.monthtips_ios != 1) {
      _showPayTips();
    } else {
      _toPay();
    }
  }

  _toPay() {
    if (state.currGood != null &&
        state.currPayConfig != null) {
      _loadOrderCreateData(
          state.currPayConfig!, state.currGood!);
    } else {
      EasyLoading.showToast("当前支付方式不支持");
    }
  }

  _showPayTips() {
    Get.dialog(ConfirmOpenDialog(
      onSuccess: () {
        _toPay();
      },
    ));
  }
}
